import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

// 通过代码，向数据库插入一条记录
public class demo1 {
    public static void main(String[] args) throws SQLException {
        // 1.先创建 DataSource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("502502");

        // 2.建立和数据库服务器之间的连接 请求-响应 交互
        Connection connection = dataSource.getConnection();

        // 3.构造sql
        String sql = "insert into student values (1, '张三')";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4.把sql发给服务器 返回值是影响到的行数
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        //5. 释放资源,关闭连接,先获取的后释放
        statement.close();
        connection.close();

    }
}
